<template>
  <div>
    <!-- 搜索 -->
  <div class="top-main">
    <el-form  class="top-form-fl stust" :model="queryParams" ref="queryRef" label-width="auto" :inline="true">
      <el-form-item label="箱号">
        <MultipleBoxNumbersDialog v-model="queryParams.refNos" />
      </el-form-item>
      <el-form-item label="账单编号" prop="billNo">
        <el-input v-model.trim="queryParams.billNo"  clearable placeholder="请输入账单编号" />
      </el-form-item>
      <el-form-item label="业务编号" prop="businessNo">
        <el-input v-model.trim="queryParams.businessNo" clearable placeholder="请输入业务编号" />
      </el-form-item>
         <el-form-item label="业务类型"  prop="refType">
         <el-select v-model="queryParams.refType" clearable style="width: 100%;" placeholder="请选择业务类型">
              <el-option
                  v-for="item in dictList.refTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
      </el-form-item>
        <el-form-item label="账单类型" prop="billType">
         <el-select v-model="queryParams.billType" clearable style="width: 100%;" placeholder="请选择账单类型">
              <el-option
                  v-for="item in tabsList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
      </el-form-item>
         <el-form-item label="账单状态" prop="billStatus">
         <el-select v-model="queryParams.billStatus" clearable style="width: 100%;" placeholder="请选择账单状态">
              <el-option
                  v-for="item in billStatusList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
      </el-form-item>
      <el-form-item label="结算单位" prop="settlementCompanyName">
        <el-input v-model.trim="queryParams.settlementCompanyName" clearable placeholder="请输入结算单位" />
      </el-form-item>
        <el-form-item  label="结算流向" prop="settlementDirection">
         <el-select v-model="queryParams.settlementDirection" clearable style="width: 100%;" placeholder="请选择结算流向">
              <el-option
                  v-for="item in settlementDirectionList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
      </el-form-item>
      <el-form-item label="核销日期">
        <el-date-picker v-model="dateObj.beginWriteOffData" type="daterange" range-separator="~" start-placeholder="开始日期"
          end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item label="创建日期">
        <el-date-picker v-model="dateObj.beginCreateDate" type="daterange" range-separator="~" start-placeholder="开始日期"
          end-placeholder="结束日期" />
      </el-form-item>
    </el-form>
     <div class="top-from-fr">
        <el-button class="top-Search" @click="getFilterData('search')" type="primary">搜索</el-button>
        <el-button class="top-Refresh" @click="resetFrome">重置</el-button>
      </div>   
    </div>
    <div style="display: flex; justify-content: flex-end;">
      <el-tooltip effect="dark" content="此按钮可选择当前页及后续页所有集装箱" placement="left">
        <template v-if="isSelectAll">
          <el-button :icon="Finished" size="small" @click="slectAll" plain class="operatingArea">全选</el-button>
        </template>
        <template v-else>
            <el-button size="small" @click="deselectAll" plain class="operatingArea">取消全选</el-button>
        </template>
      </el-tooltip>
      <el-dropdown style="margin-left: 20px;">
        <el-button :icon="Grid" size="small">
          批量操作
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="batchTap(1)">导出</el-dropdown-item>
            <!-- <el-dropdown-item @click="batchTap(2)">编辑</el-dropdown-item> -->
            <el-dropdown-item @click="batchTap(3)">删除</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <el-button type="primary" size="small" :icon="Document" @click="batchTap(7)" style="margin-left: 20px;">申请发票</el-button>
      <el-button type="primary" size="small" :icon="Document" @click="batchTap(6)" style="margin-left: 20px;">核销</el-button>
      <el-button type="primary" size="small" :icon="FolderDelete" @click="batchTap(4)" style="margin-left: 20px;">撤销</el-button>
      <el-button type="primary" size="small" :icon="DocumentChecked" @click="batchTap(5)" style="margin:0 20px;">对账</el-button>
    </div>
    <!-- <div class="main-cent" style="width: 20%;">
      <el-tabs v-model="queryParams.billType" class="demo-tabs" @tab-change="handleClick">
        <el-tab-pane v-for="item in tabsList" :key="item.value" :label="item.label" :name="item.value"></el-tab-pane>
      </el-tabs>
    </div> -->
    <Table ref="tableRef" v-bind="tableData" :allId="allId" :isAllCheck="isAllCheck" :getBillSumAmountAll="getBillSumAmountAll" @editPermissions="editPermissions" @editPermissionsInfo="editPermissionsInfo" @verificationTap="verificationTap" @revocationTap="revocationTap" @deleteBox="deleteBox"
        @pageChange="pageChange" @updateSelectAll="updateSelectAll" :disableHeaderCheckbox="disableHeaderCheckbox">
    </Table>
    <!-- 核销 -->
    <verificationModalForm ref="verificationModalMormRef"  @verificationMode="getFilterData('other')"></verificationModalForm>
    <!-- 批量导入 -->
    <uploadModalForm ref="uploadModalMormRef"  @uploadMode="getFilterData('other')"></uploadModalForm>
    <!-- 批量开发票 -->
    <applyInvoiceFrom ref="applyInvoiceModalMormRef"  @uploadMode="getFilterData('other')"></applyInvoiceFrom>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onActivated,computed,toRefs } from 'vue'
import Table from '@/components/table'
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus,Grid,FolderDelete,Document,DocumentChecked } from '@element-plus/icons-vue'
import { getTableList, deleteIds ,getBillSumAmount,updateBillStatus} from '@/api/financial/bills'
import dictList from '@/utils/dictList'


import MultipleBoxNumbersDialog from '@/components/dialog/multipleBoxNumbersDialog.vue'
import verificationModalForm from '@/views/financialManage/bills/components/verificationModalForm.vue'
import uploadModalForm from '@/views/financialManage/bills/components/uploadModalForm.vue'
import applyInvoiceFrom from '@/views/financialManage/bills/components/applyInvoiceFrom.vue'

import { useRouter } from 'vue-router'
const verificationModalMormRef = ref()
const queryRef = ref()
const uploadModalMormRef=ref()
const applyInvoiceModalMormRef=ref()
const tabsList=ref([
{ label: '业务账单', value: 5 },
{ label: '超期费账单', value: 10},
{ label: '堆存费账单', value: 15},
{ label: '堆场超期费账单', value: 20},
{ label: '其他', value: 25}
])
const tabsList1 = {5: '业务账单', 10: '超期费账单', 15: '堆存费账单',20:'堆场超期费账单' ,25:'其他'}

const settlementDirectionList=ref([
  {
    value:1,
    label:'应收'
  },{
    value:-1,
    label:'应付'
  },
])

const billStatusList=ref([
  {
    value:5,
    label:'未对账'
  },{
    value:10,
    label:'已撤销'
  },{
    value:15,
    label:'未核销'
  },{
    value:20,
    label:'部分核销'
  },{
    value:25,
    label:'已核销'
  },
])


const dateObj=ref({
  beginWriteOffData:null,
  beginCreateDate:null,
})
const data = reactive({
  queryParams: {
    refNos:'',
    billNo:'',
    businessNo:'',
    settlementDirection:'',
    settlementCompanyName:'',
    billType:'',
    beginWriteOffTime:'',
    endWriteOffTime:'',
    beginCreateTime:'',
    endCreateTime:'',
    pageNum: 1,
    pageSize: 10,
  },
});
const { queryParams } = toRefs(data);

onActivated(() => {
  getFilterData('other')
})
// 基础数据
const tableData = reactive({
  header: [
    { key: 'businessNo', key2: 'businessNo',colWidth: '200', title: '业务编号',type: '/',  isCheck: true },
    { key: 'billNo', colWidth: '200', title: '账单编号', type: '<a>',command: 'editPermissionsInfo', isCheck: true ,},
    { key: 'refNo', key2: 'refNo', colWidth: '200', title: '箱号', type: '/', isCheck: true },
    { key: 'refType', colWidth: '100', title: '业务类型', type: 'filter', filter: dictList.refTypeList1, isCheck: true },
    { key: 'billType', colWidth: '100', title: '账单类型', type: 'filter', filter:tabsList1, isCheck: true },
    { key: 'deductBillCnyAmount',key2: 'deductBillUsdAmount', colWidth: '150', title: '账单金额', type: 'amount', isCheck: true },
    { key: 'paidBillCnyAmount',key2: 'paidBillUsdAmount', colWidth: '150', title: '已付金额', type: 'amount', isCheck: true },
    { key: 'unpaidBillCnyAmount',key2: 'unpaidBillUsdAmount', colWidth: '150', title: '未付金额', type: 'amount', isCheck: true },
    { key: 'billStatus', colWidth: '100', title: '账单状态', type: 'billStatus', isCheck: true },
    { key: 'settlementDirection', colWidth: '100', title: '结算流向', type: 'settlementDirection', isCheck: true },
    { key: 'settlementCompanyName', colWidth: '200', title: '结算单位', type: 'text', isCheck: true },
    { key: 'writeOffTime', colWidth: '150', title: '核销日期', type: 'date', isCheck: true },
    { key: 'createTime', colWidth: '150', title: '创建日期', type: 'date', isCheck: true },
    {
      key: 'operate',
      colWidth: '200',
      title: '操作',
      type: 'operate',
      fixed: 'right',
      isCheck: true,
      buttons: [
        {
          // icon: 'Edit',
          type: 0,  
          command: 'editPermissions',
          // content: '编辑',
          name:'编辑',
          isShow: (row: any) => {
            return row.billStatus == 5;
          },
        },
        {
          // icon: 'Document',
          type: 0, 
          command: 'verificationTap',
          // content: '核销',
          name:'核销',
          isShow: (row: any) => {
            return  row.billStatus == 15 || row.billStatus == 20;
          },
        },
        {
          // icon: 'Failed',
          type: 0,
          command: 'revocationTap',
          // content: '撤销',
          name:'撤销',
          isShow: (row: any) => {
            return row.billStatus == 5 || row.billStatus == 15;
          },
        }
      ]
    }
  ],
  data: [],
  config: {
    isSelection: true,
    isList: false,
    isPagination: true, // 是否分页
    total: 0, // 总条数
    loading: false,
    isRealName: false, // 是否已经实名认证
  }
})
const tableRef = ref({ multipleSelection: [] })
const selection = computed(() => {
  let checkAllItem = []
  if(isSelectAll.value){
    checkAllItem = tableRef.value.multipleSelection
  }else{
    checkAllItem = allId.value
  }

  let ids: any[] = []
  checkAllItem.map((item: any) => {
    ids.push(item.id)
  })
  return ids
})
//tabs切换 列表字段是否显示
const handleClick=()=>{
  tableRef.value.clearCheckAll()
  getFilterData('other')
  tableData.header.forEach((item)=>{
     if(queryParams.value.billType == 10){
        if(item.key=='writeOffTime'){
         item.title='收款日期'
        }
      }else{
         if(item.key=='writeOffTime'){
          item.title='核销日期'
          }
      }
    if(queryParams.value.billType == 15){
      if(item.key=='businessNo'){
        item.isCheck=false
      }
      if(item.key=='refType'){
        item.isCheck=false
      }
      if(item.key=='settlementDirection'){
        item.isCheck=false
      }
    }else{
      if(item.key=='businessNo'){
        item.isCheck=true
      }
       if(item.key=='refType'){
        item.isCheck=true
      }
      if(item.key=='settlementDirection'){
        item.isCheck=true
      }
    }
  })
  tableData.header[0].billNo=true
}
// 重置搜索数据
const resetFrome = () => {
  queryRef.value.resetFields()
  queryParams.value.refNos = ''
  dateObj.value.beginWriteOffData = null
  dateObj.value.beginCreateDate = null
  queryParams.value.beginWriteOffTime = ''
  queryParams.value.endWriteOffTime = ''
  queryParams.value.beginCreateTime = ''
  queryParams.value.endCreateTime = ''
  getFilterData('other')
}
const showDataIds = ref([]) //列表显示内容id集合
// 费用合计
const getBillSumAmountAll=ref({})
// 搜索数据
const getFilterData = (type:string) => {
  if (dateObj.value.beginWriteOffData) {
    queryParams.value.beginWriteOffTime = dateObj.value.beginWriteOffData[0]
    queryParams.value.endWriteOffTime = dateObj.value.beginWriteOffData[1]
  }
  if (dateObj.value.beginCreateDate) {
    queryParams.value.beginCreateTime = dateObj.value.beginCreateDate[0]
    queryParams.value.endCreateTime = dateObj.value.beginCreateDate[1]
  }
  let queryData = JSON.parse(JSON.stringify(queryParams.value))
  if(queryData.refNos && queryData.refNos!=''){
    queryData.refNos=queryParams.value.refNos.split(',')
  }else{
   delete queryData.refNos
  }
  getTableList(queryData).then(res => {
    tableData.data = res.data.list.sort((a, b) => a.sort - b.sort)
    tableData.config.total = res.data.total
    showDataIds.value.length = 0
    if(type == "search"){
      showDataIds.value = res.data.list.map(item => item.id)
    }
    getBillSumAmount(queryData).then(res => {
      getBillSumAmountAll.value = res.data
     
    })
  })
}

// 编辑
const router = useRouter();
const editPermissions = (row) => {
    // router.push('billsInfo')
    router.push({ 
      path: '/financialManage/billsInfo', 
      query: { 
        id:row.id, 
        billType:row.billType,
        type:1
      } 
    })
}
//查看
const editPermissionsInfo = (row) => {
    // router.push('billsInfo')
    router.push({ 
      path: '/financialManage/billsInfo', 
      query: { 
        id:row.id, 
        billType:row.billType,
        type:2
      } 
    })
}
//核销
const verificationTap=(row)=>{
    verificationModalMormRef.value.onShow(row.id,row.refType,1)
}
//单独撤销
const revocationTap=(row)=>{
     ElMessageBox.confirm(
    '您确定要撤销所勾选的账单？',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      let data={
        ids:[],
        billStatus:10
      }
      data.ids.push(row.id)
      updateBillStatus(data).then((res) => {
        ElMessage.success('操作成功')
        getFilterData('other')
      })
    })
}

// 批量操作
const batchTap= (type) => {
  //type  导出  2编辑  3删除
  let row = selection.value
  if(type==1){
    if(row.length==0){
      ElMessage.warning('请选择要导出的数据');
        return false
    }
      let billType=[]
    //获取账单类型
    tableData.data.map(item=>{
      row.map(itemInfo=>{
        if(item.id==itemInfo){
          billType.push(item.billType)
        }
      })
    })
    uploadModalMormRef.value.onShow(row,billType)
  }else if(type==2){

  }else if(type==3){
    if(row.length==0){
      ElMessage.warning('请选择要删除的数据');
        return false
    }
    deleteBox(row)
  }else if(type==4){
    if(row.length==0){
      ElMessage.warning('请选择要撤销的数据');
        return false
    }
    revocationBox(row,type)
  }else if(type==5){
    if(row.length==0){
      ElMessage.warning('请选择要对账的数据');
        return false
    }
    revocationBox(row,type)
  }else if(type==6){
    if(row.length==0) return ElMessage.warning('请选择要核销的数据');
    let attrType=[]
    let billStatusIn=false
    //获取账单类型
    tableData.data.map(item => {
      row.map(itemInfo => {
        if(item.id == itemInfo){
          attrType.push(item.refType)
          if(item.billStatus==25){
            billStatusIn = true
          }
        }
      })
    })
    if(billStatusIn)return ElMessage.warning('已核销状态不能再次核销');

    let attrTypeSet=new Set(attrType).size === 1
    if(!attrTypeSet) return ElMessage.warning('您所选账单业务类型需相同');

    verificationModalMormRef.value.onShow(row,attrType[0],2)
  }else if(type==7){
    if(row.length==0) return ElMessage.warning('请选择要申请发票的数据');
    // let attrType=[]
    let billStatusIn=false
    let billList=[]
    //获取账单类型
    tableData.data.map(item => {
      row.map(itemInfo => {
        if(item.id == itemInfo){
          if(item.billStatus==15 || item.billStatus==20){
            billStatusIn = true
            let obj={
              billId:item.id,
              billNo:item.billNo
            }
            billList.push(obj)
          }
        }
      })
    })
    if(!billStatusIn)return ElMessage.warning('已核销和部分核销可以开发票');

    applyInvoiceModalMormRef.value.onShow(billList)

  }
}
//批量状态修改操作
const revocationBox = (row,type) => {
  let centent=''
  let billStatus=10
  if(type==4){
     centent='您确定要撤销所勾选的账单？'
     billStatus=10
  }else if(type==5){
     centent='您确定所勾选的账单已完成对账？'
     billStatus=15
  }
    ElMessageBox.confirm(
    centent,
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      let data={
        ids:row,
        billStatus:billStatus
      }
      updateBillStatus(data).then((res) => {
        ElMessage.success('操作成功')
        getFilterData('other')
      })
    })
}
//删除操作
const deleteBox = (row) => {
  ElMessageBox.confirm(
    '您确定要删除所勾选的账单？',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      let data=[]
      if(row?.id){
        //单独删除
        data.push(row.id)
      }else{
        //批量
        data=row
      }
      deleteIds(data).then((res) => {
        ElMessage.success('删除成功')
        getFilterData('other')
      })
    })
}
// // 翻页控制
const pageChange = (val) => {
  queryParams.value.pageNum=val.pageNum
  queryParams.value.pageSize=val.pageSize
  getFilterData('other')
}


const isSelectAll = ref(true) // true:显示全选按钮  false：显示取消全选按钮
const allId = ref([]) // 使用全选功能时使用
const isAllCheck = ref(false) //是否使用全选功能
const checkAll = ref([]) //点击全选按钮时 选中列表所有内容（包含当前页和所有后续页）

const disableHeaderCheckbox = ref(false) // true:禁用表头全选/全取消 选择框 false:开启 表头全选/全取消 选择框
const slectAll = async(val:any) =>{
    checkAll.value = []
    await getTableList({ pageNum:1,pageSize:10000,billType: queryParams.value.billType}).then(res =>{ 
      if(res.code == "00000" && res.data.list && res.data.total){
        isSelectAll.value = false
        disableHeaderCheckbox.value = true
        res.data.list.forEach(item => {
          checkAll.value.push(item)
        })
        isAllCheck.value = true
        allId.value = checkAll.value
        tableRef.value.checkAll()
      }else{
        ElMessage.error("全选失败，请刷新页面，或者手动选择")
      }
 })
}
const deselectAll = () =>{
  allId.value = []
  disableHeaderCheckbox.value = false
  tableRef.value.clearCheckAll()
  isSelectAll.value = true
}

const updateSelectAll = (val) => {
  allId.value = val
  // console.log("11111",allId.value)
}

</script>

<style scoped>
.choose-item-2 {
  margin-left: 20px;
}
.stust{
  padding:0 20px 30px 20px;
}
.choose-item-3 {
  display: block;
  margin-left: 20px;
}
.main-cent{
  padding: 0 10px;
}
.header-title{
  border-left: 4px solid #2158F3;
  padding-left: 8px;
  line-height: 18px;
}

</style>